//专供竖版列表页
const app = getApp();
var server = require('../../utils/server');
var common = require('../../utils/common');
var counttime = null;
Page({
  data: {
    countH: '00',
    countM: '00',
    countS: '00',
    eventid: "",
    isOverDay: false,
    restDay: 0,
    eventDetail: "",
    goodsList: "",
    templateContent: "",
    totalCartNum: 0,
    isLogin: true,
    showLoginPop: false,
    showHome: false,
    nowtimestamp: "",
    scene: "",
    curGoodsId: "",
    channelId: "", //渠道ID
    isDisableLog: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    this.data.eventid = options.eventid;
    this.data.scene = options.scene == undefined ? '' : options.scene;
    this.data.channelId = options.cid == undefined ? '' : options.cid;
    this.setData({
      nowtimestamp: (Date.parse(new Date())) / 1000
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (app.globalData.sdkversion >= 283 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      wx.hideHomeButton();
    }
    if (getCurrentPages().length == 1) {
      this.setData({
        showHome: true
      })
    }
    this.getDetail();
    this.getUserInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    clearTimeout(counttime)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log(counttime)
    clearTimeout(counttime)
  },

  getDetail() {
    wx.stopPullDownRefresh();
    if (this.data.scene != '' && this.data.scene.indexOf('DECODE') > -1) {
      this.decodeScene();
    } else {
      this.getEventDetail();
    }
  },
  getEventDetail() {
    server.postJSON(common.storePath + 'event/detail/', {
      "event_id": this.data.eventid
    }, res => {
      if (this.data.channelId != '') {
        wx.setStorage({
          key: 'channelid',
          data: this.data.channelId
        })
      }
      var res = res.data;
      if (res.errno == "0") {
        wx.hideNavigationBarLoading();
        common.hideLoading();
        this.setData({
          eventDetail: res.data.event,
          templateContent: res.data.event.template_content,
          goodsList: res.data.goods,
        })
        if (app.globalData.sdkversion > 210 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
          wx.setBackgroundColor({
            backgroundColorTop: this.data.templateContent.background, // 顶部窗口的背景色为白色
            backgroundColorBottom: this.data.templateContent.background, // 底部窗口的背景色为白色
          })
        }
        clearTimeout(counttime);
        if (res.data.event.status == 'going') {
          this.countTime(res.data.event.end_time)
        } else if (res.data.event.status == 'wait') {
          this.countTime(res.data.event.start_time)
        }
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  //解析scene
  decodeScene() {
    server.postJSON(common.storePath + 'voucher/scenedecode/', {
      "scene": this.data.scene
    }, res => {
      var data = res.data;
      if (res.data.errno == '0') {
        console.log(data);
        this.data.eventid = data.data.event_id;
        if (data.data.channel_id != '') {
          this.data.channelId = data.data.channel_id;
        }
        this.getEventDetail();
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  //获取用户信息
  getUserInfo() {
    wx.login({
      success: resp => {
        wx.getUserInfo({
          success: res => {
            var code = resp.code;
            this.data.userParams = {
              "js_code": code,
              "encryptedData": res.encryptedData,
              "iv": res.iv,
              "userinfo": res.userInfo,
              "longitude": app.globalData.longitude,
              "latitude": app.globalData.latitude,
              "province": app.globalData.locateProvince,
              "city": app.globalData.locateCity
            }
            var that = this;
            server.login(common.basePath + 'miniprogram/login/', that.data.userParams, function (res) {
              if (res.data.errno == "0") {
                app.globalData.sso = res.data.data.sso;
                wx.setStorage({
                  key: "sso",
                  data: res.data.data.sso,
                  success: res => {
                    that.getTotalCartNum();
                    that.data.isLogin = true;
                    app.globalData.isGetWxUserinfo = true;
                  }
                })
              } else {
                that.data.isLogin = false;
                common.showErrorToast(res.data.errmsg);
              }
            })
          },
          fail: res => {
            this.data.isLogin = false;

          }
        })
      },
      fail: res => {
        this.data.isLogin = false;
      }
    })
  },
  // 倒计时
  countTime(time) {
    //获取当前时间  
    var time = time;
    var date = new Date();
    var now = date.getTime() / 1000;
    //时间差  
    var leftTime = time - now;
    //定义变量 d,h,m,s保存倒计时的时间  
    var d, h, m, s;
    d = Math.floor(leftTime / 60 / 60 / 24);
    if (leftTime > 0) {
      h = d * 24 + Math.floor(leftTime / 60 / 60 % 24);
      m = Math.floor(leftTime / 60 % 60);
      s = Math.floor(leftTime % 60);
    } else if (this.data.eventDetail.status == 'going' && leftTime <= 0) {
      this.getDetail();
    } else if (this.data.eventDetail.status == 'wait' && leftTime <= 0) {
      this.getDetail();
    }
    //将0-9的数字前面加上0，例1变为01
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);

    function checkTime(i) {
      if (i < 10) {
        i = "0" + i;
      }
      return i;
    }
    //将倒计时赋值到div中
    if (d <= 0) {
      this.setData({
        countH: h,
        countM: m,
        countS: s,
        isOverDay: false
      })
    } else {
      this.setData({
        restDay: d,
        isOverDay: true
      })
    }
    var that = this;
    counttime = setTimeout(function() {
      that.countTime(time)
    }, 1000);
  },
  goToProDetail(e) {
    console.log(e.currentTarget.dataset.goodsid);
    this.data.curGoodsId = e.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: 'productDetailM?eventid=' + this.data.eventDetail.event_id + '&&goodsid=' + e.currentTarget.dataset.goodsid + '&&cid=' + this.data.channelId,
    })
  },
  onPullDownRefresh() {
    this.getDetail();
    this.getTotalCartNum();
  },
  getTotalCartNum() {
    server.postJSON(common.storePath + 'eventcart/num', '', res => {
      var res = res.data;
      if (res.errno == "0") {
        this.setData({
          totalCartNum: res.data
        })
      } else {
        if (res.errno == '100012' || res.errno == '100013') {
          this.data.isLogin = false;
        } else {
          this.data.isLogin = true;
          common.showErrorToast(res.errmsg);
        }
      }
    })
  },
  goToCart() {
    if (this.data.isLogin) {
      app.globalData.cartIndexType = 1;
      wx.navigateTo({
        url: '../../pages/cart/cartIndexSec',
      })
    } else {
      this.setData({
        showLoginPop: true
      })
    }
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../../pages/common/agreement',
    })
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false
      })
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              var code = resp.code;
              this.data.userParams = {
                "js_code": code,
                "encryptedData": res.encryptedData,
                "iv": res.iv,
                "userinfo": res.userInfo,
                "longitude": app.globalData.longitude,
                "latitude": app.globalData.latitude,
                "province": app.globalData.locateProvince,
                "city": app.globalData.city
              }
              var that = this;
              server.login(common.basePath + 'miniprogram/login/', this.data.userParams, function(res) {
                if (res.data.errno == "0") {
                  wx.setStorage({
                    key: "sso",
                    data: res.data.data.sso,
                    success: res => {
                      that.getTotalCartNum();
                      that.data.isLogin = true
                      app.globalData.isGetWxUserinfo = true
                      common.showErrorToast('登录成功')
                      that.setData({
                        isDisableLog: false
                      })
                    }
                  })
                } else {
                  that.setData({
                    isDisableLog: false
                  })
                  common.showErrorToast(res.data.errmsg)
                }
              })
            }
          })
        }
      })
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  onShareAppMessage(options) {
    console.log('share')
    var detail = this.data.eventDetail;
    var shareObj = {};
    console.log(detail.share_pic)
    if (detail.share_pic != ""&& detail.share_pic != undefined) {
      var img = detail.share_pic + '-goods_share';
      shareObj = {
        title: detail.name,
        path: '/membership_supply/pages/productListsM2?eventid=' + detail.event_id + '&&cid=' + this.data.channelId,
        imageUrl: img,
        success: function(res) {
          console.log("分享成功")
        },
        fail: function() {
          console.log("分享失败")
        }
      }
    } else {
      shareObj = {
        title: detail.name,
        path: '/membership_supply/pages/productListsM2?eventid=' + detail.event_id + '&&cid=' + this.data.channelId,
        success: function(res) {
          console.log("分享成功")
        },
        fail: function() {
          console.log("分享失败")
        }
      }
    }
    console.log(shareObj)
    return shareObj;
  },
  goToIndex() {
    wx.switchTab({
      url: '../../pages/index/index',
    })
  },
  goToActivity(e) {
    wx.navigateTo({
      url: '../../activity/pages/activityIndex?scene=' + e.currentTarget.dataset.id,
    })
  }
})